package com.tc.socket.config;

import lombok.extern.slf4j.Slf4j;
import org.apache.tomcat.util.net.openssl.ciphers.Authentication;
import org.springframework.messaging.Message;
import org.springframework.messaging.MessageChannel;
import org.springframework.messaging.simp.stomp.StompCommand;
import org.springframework.messaging.simp.stomp.StompHeaderAccessor;
import org.springframework.messaging.support.ChannelInterceptor;

import java.security.Principal;

/**
 * @Auther: tianchao
 * @Date: 2022/4/2 13:20
 * @Description:
 */
@Slf4j
public class MyChannelInterceptor  implements ChannelInterceptor {

    @Override
    public Message<?> preSend(Message<?> message, MessageChannel channel) {
        StompHeaderAccessor accessor = StompHeaderAccessor.getAccessor(message, StompHeaderAccessor.class);
        final StompCommand command = accessor.getCommand();
        log.info("消息{}，命令：{},channel: {}",message,command,channel);
        // ...
        if (StompCommand.CONNECT.equals(accessor.getCommand())) {
            PrincipalImpl principal = new PrincipalImpl();
            principal.setName("aaaaa");
            accessor.setUser(principal);
            return message;
        }
        return message;
    }

    @Override
    public void postSend(Message<?> message, MessageChannel channel, boolean sent) {
        log.info("====>postSend  message: {}, channel: {} ,sent : {}",
                message,
                channel,
                sent
        );
    }

    @Override
    public void afterSendCompletion(Message<?> message, MessageChannel channel, boolean sent, Exception ex) {
        log.info("====>afterSendCompletion  message: {}, channel: {} ,sent : {},ex: {}",
                message,
                channel,
                sent,
                ex
        );
    }

    @Override
    public boolean preReceive(MessageChannel channel) {
        log.info("====>preReceive  channel: {}",
                channel
        );
        return true;
    }

    @Override
    public Message<?> postReceive(Message<?> message, MessageChannel channel) {
        log.info("====>postReceive  message: {},channel: {}",
                message,
                channel
        );
        return message;
    }

    @Override
    public void afterReceiveCompletion(Message<?> message, MessageChannel channel, Exception ex) {
        log.info("====>postReceive  message: {},channel: {},ex: {}",
                message,
                channel,
                ex
        );
    }
}
